package com.morse.mycomputer.splash

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.morse.common.IntentUtils
import com.morse.mycomputer.R
import com.morse.mycomputer.home.HomeActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

@SuppressLint("CustomSplashScreen")
class SplashActivity : AppCompatActivity() {

    private var ivSplash: ImageView? = null
    private var tvSkip: TextView? = null

    private val time: Int = 5
    private var mCountDown: CoroutineScope? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        ivSplash = findViewById<ImageView>(R.id.iv_splash)
        tvSkip = findViewById<TextView>(R.id.tv_skip)

        lifecycleScope.launch {
            flow {
                (time downTo 1).forEach {
                    delay(1000)
                    emit(it)
                }
            }.onStart {
                mCountDown = this@launch
            }.onCompletion {
                Log.i("SplashActivity", "倒计时结束")
                IntentUtils.jumpPage(this@SplashActivity, HomeActivity::class.java)
                finish()
            }.catch {
                error(it.message ?: "count down 出现问题")
            }.collect { index->
                Log.i("SplashActivity", "剩余 $index 秒")
                tvSkip?.let {
                    it.text = getString(R.string.skip, index)
                }
            }
        }

        ivSplash?.setOnClickListener {

        }

        tvSkip?.setOnClickListener {
            IntentUtils.jumpPage(this@SplashActivity, HomeActivity::class.java)
            finish()
        }
    }
}